package cn.ultrarisk.scadmin.manager.support;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2013-9-16
 * @since V1.0
 */
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    @Override
    public void destroy() throws Exception {
        SpringContextHolder.applicationContext = null;
    }

    public static ApplicationContext getApplicationContext() {
        if (SpringContextHolder.applicationContext != null) {
            return SpringContextHolder.applicationContext;
        }
        throw new RuntimeException("SpringContextHolder.applicationContext is null");
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        if (SpringContextHolder.applicationContext != null) {
            return (T) SpringContextHolder.applicationContext.getBean(name);
        }
        throw new RuntimeException("SpringContextHolder.applicationContext is null");
    }

    public static <T> T getBean(Class<T> clazz) {
        if (SpringContextHolder.applicationContext != null) {
            return SpringContextHolder.applicationContext.getBean(clazz);
        }
        throw new RuntimeException("SpringContextHolder.applicationContext is null");
    }
}
